package com.tc.banana.framework.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @Description:TODO 转型操作工具类
 * @author: wangdongdong  
 * @date:   2016年3月31日 上午10:08:40   
 *
 */
public class CastUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(CastUtil.class);

	public static String castString(Object obj){
		return castString(obj, "");
	}
	
	public static String castString(Object obj, String defaultValue){
		return obj != null ? String.valueOf(obj) : defaultValue;
	}
	
	public static int castInt(Object object) {
		return castInt(object, 0);
	}
	
	public static int castInt(Object obj, int defaultValue){
		int value = defaultValue;
		if(obj != null){
			String strValue = castString(obj);
			if(StringUtils.isNotEmpty(strValue)){
				try {
					value = Integer.parseInt(strValue);
				} catch (NumberFormatException e) {
					value = defaultValue;
					LOGGER.error("cast object to int value faulure",e);
					throw new NumberFormatException("cannot cast " + strValue + "to int value");
				}
			}
		}
		return value;
	}

	public static Integer castInteger(Object obj, Integer defaultValue){
		return Integer.valueOf(castInt(obj, defaultValue));
	}
	
	public static Integer castInteger(Object obj){
		return Integer.valueOf(castInt(obj));
	}
	
	public static boolean castBoolean(Object obj){
		return castBoolean(obj, false);
	}
	
	public static boolean castBoolean(Object obj, boolean defaultValue){
		boolean value = defaultValue;
		if(obj != null){
			value = Boolean.parseBoolean(castString(obj));
		}
		return value;
	}
}
